﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace JQuery.WebKit.Common.Serialization
{
    public static class XmlSerialization
    {
        #region public static object FromXML(string xmlString, Type objectType)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="xmlString"></param>
        /// <param name="objectType"></param>
        /// <returns></returns>
        public static object FromXML(string xmlString, Type objectType)
        {
            XmlSerializer resultSerializer = new XmlSerializer(objectType);
            MemoryStream ms = new MemoryStream(ASCIIEncoding.UTF8.GetBytes(xmlString));
            ms.Position = 0;

            object obj = resultSerializer.Deserialize(ms);

            ms.Close();
            ms.Dispose();
            return obj;
        }
        #endregion

        #region public static string ToXML(object objectInstance)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="objectInstance"></param>
        /// <returns></returns>
        public static string ToXML(object objectInstance)
        {
            if (objectInstance.GetType() == typeof(NameValueCollection))
            {
                SoapFormatter ser = new SoapFormatter();
                MemoryStream ms = new MemoryStream();
                ser.Serialize(ms, objectInstance as NameValueCollection);
                byte[] b = ms.GetBuffer();
                string s = Encoding.Default.GetString(b);
                ms.Close();
                return s;
            }
            XmlSerializer resultSerializer = new XmlSerializer(objectInstance.GetType()); ;
            StringBuilder resultBuilder = new StringBuilder();
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = ("    ");
            settings.Encoding = Encoding.UTF8;
            settings.OmitXmlDeclaration = true;
            XmlWriter writer = XmlTextWriter.Create(resultBuilder, settings);
            resultSerializer.Serialize(writer, objectInstance);
            writer.Flush();
            writer.Close();

            return resultBuilder.ToString();
        }
        #endregion
    }
}
